package com.chinatechstar.file.controller;

import com.alibaba.fastjson.JSONObject;
import com.chinatechstar.component.commons.consts.Consts.MQ_TYPE;
import com.chinatechstar.component.commons.controller.BaseController;
import com.chinatechstar.component.commons.entity.MqData;
import com.chinatechstar.component.commons.service.AliyunOssService;
import com.chinatechstar.component.commons.supports.PageData;
import com.chinatechstar.file.config.RabbitMQConfig;
import com.chinatechstar.file.entity.CerFileImpRecord;
import com.chinatechstar.file.service.FileImpRecordService;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.chinatechstar.component.commons.result.ActionResult;
import com.chinatechstar.component.commons.result.ListResult;
import com.chinatechstar.component.commons.result.ResultBuilder;
import com.chinatechstar.component.commons.utils.FileUtils;
import com.chinatechstar.file.service.FileService;
import com.chinatechstar.file.vo.FileVO;

/**
 * 文件信息的控制层
 *
 * @author wlei
 * @版权所有 上海至界信息科技有限公司
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController extends BaseController {

    @Autowired
    private FileService fileService;
    @Autowired
    private FileImpRecordService fileImpRecordService;
    @Autowired
    private RabbitTemplate template;

    @Autowired
    private AliyunOssService aliyunOssService;

    /**
     * 查询文件分页
     *
     * @param fileVO 文件前端参数
     * @return
     */
    @GetMapping(path = "/queryFile")
    public ListResult<Object> queryFile(FileVO fileVO) {
        Map<String, Object> data = fileService.queryFile(fileVO.getCurrentPage(),
                                                         fileVO.getPageSize(),
                                                         fileVO.getOriginalFilename(),
                                                         fileVO.getSorter());
        return ResultBuilder.buildListSuccess(data);
    }

    @PostMapping(value = "/uploadFileToOss", consumes = {"multipart/form-data"})
    public ListResult<Object> queryFile(@RequestParam(name = "file", required = true) MultipartFile file) {
        String s = aliyunOssService.uploadMultipartFile(file);
        Map<String, Object> data = new HashMap<>();
        data.put("filePath", s);
        return ResultBuilder.buildListSuccess(data);
    }

    /**
     * 删除文件
     *
     * @param id 文件ID
     * @return
     * @throws IOException
     */
    @PostMapping(path = "/deleteFile")
    public ActionResult deleteFile(@RequestParam(name = "id", required = true) Long[] id)
        throws IOException {
        fileService.deleteFile(id);
        return ResultBuilder.buildActionSuccess();
    }


    /**
     * 上传文件
     *
     * @param file       文件资源
     * @param id         用户ID
     * @param uploadType 上传类型
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/uploadFile", consumes = {"multipart/form-data"})
    public ListResult<Object> uploadFile(@RequestParam(name = "file", required = true) MultipartFile file,
                                         @RequestParam(name = "id", required = true) Long id,
                                         @RequestParam(name = "uploadType", required = false) String uploadType)
        throws IOException {
        //fileService.uploadFile(file, id, uploadType);
        long fileId = fileService.uploadFilePlus(file, id, uploadType);
        Map<String, Object> data = new HashMap<>();
        data.put("msg", "上传成功");
        data.put("fileId", String.valueOf(fileId));
        return ResultBuilder.buildListSuccess(data);
    }
    @PostMapping(value = "/uploadFileAndGetPath")
    public ListResult<Object> uploadFileAndGetPath(@RequestParam("file") MultipartFile file)
            throws IOException {
        log.info("上传文件");
        PageData pageData = getPageData();
        String userId = (String) pageData.get("user");
        // 文件存储位置
        String filePath = fileService.uploadFile4EndoscopicDiagnosis(file, userId);
        // 获取文件名称
        String originalFilename = new File(filePath).getName();

        Map<String, Object> data = new HashMap<>();
        data.put("filePath", filePath);
        data.put("originalFilename", originalFilename);
        return ResultBuilder.buildListSuccess(data);
    }
    /**
     * 上传内镜诊断文件
     *
     * @param file
     * @return
     */
    @PostMapping(value = "/uploadFile4CerEndoscopicDiagnosis")
    public ListResult<Object> uploadFile4CerEndoscopicDiagnosis(@RequestParam("file") MultipartFile file)
        throws IOException {
        log.info("上传内镜诊断文件");
        PageData pageData = getPageData();
        String userId = (String) pageData.get("user");
        // 文件存储位置
        String filePath = fileService.uploadFile4EndoscopicDiagnosis(file, userId);
        // 获取文件名称
        String originalFilename = new File(filePath).getName();

        Map<String, Object> data = new HashMap<>();
        data.put("filePath", filePath);
        data.put("originalFilename", originalFilename);
        return ResultBuilder.buildListSuccess(data);
    }

    /**
     * 上传内镜诊断报告单
     *
     * @param file
     * @return
     * @throws IOException
     */

    @PostMapping(value = "/uploadFile4Report")
    public ListResult<Object> uploadFile4Report(@RequestParam("file") MultipartFile file)
        throws IOException {
        log.info("上传内镜诊断报告单");
        PageData pageData = getPageData();
        String userId = (String) pageData.get("user");
        // 文件存储位置
        String filePath = fileService.uploadFile4Report(file, userId);
        // 获取文件名称
        String originalFilename = new File(filePath).getName();

        Map<String, Object> data = new HashMap<>();
        data.put("filePath", filePath);
        data.put("originalFilename", originalFilename);
        return ResultBuilder.buildListSuccess(data);
    }

    @PostMapping(value = "/uploadFile4CerDataInit")
    public ListResult<Object> uploadFile4CerDataInit(@RequestParam("file") MultipartFile file)
        throws IOException {
        log.info("上传农癌初始数据");

        PageData pageData = getPageData();
        String userId = (String) pageData.get("user");

        // 上传文件
        String filePath = fileService.uploadFile4DataInit(file, userId);

        // 上传完成后将数据记录到数据库中
        CerFileImpRecord record = getFileImpRecord(userId, filePath);

        // 写入数据库
        int insert = fileImpRecordService.insert(record);

        // 将写入结构发送到消息队列
        if (insert > 0) {
            String tradeNo = record.getTradeNo();
            MqData mqData = new MqData();
            mqData.setType(MQ_TYPE.PARSE_CER_SYSTEM_DATA_INIT);
            mqData.setTradeNo(tradeNo);
            template.convertAndSend(RabbitMQConfig.EXCHANGE_NAME,
                                    RabbitMQConfig.ROUTING_KEY,
                                    JSONObject.toJSONString(mqData));
        }

        Map<String, Object> data = new HashMap<>();
        data.put("filePath", filePath);
        return ResultBuilder.buildListSuccess(data);
    }

    /**
     * 详情上报中的批量内镜,病理报告单上传
     *
     * @param file
     * @return
     */
    @PostMapping(value = "/uploadFile4CerDetailReport")
    public ListResult<Object> uploadFile4CerDetailReport(@RequestParam("file") MultipartFile file)
        throws IOException {
        log.info("详情上报中的批量内镜,病理报告单上传");

        // 上传文件的用户
        PageData pageData = getPageData();
        String userId = (String) pageData.get("user");

        // 上传文件
        String filePath = fileService.uploadFile4DetailReport(file, userId);

        // 上传完成后将数据记录到数据库中
        CerFileImpRecord record = getFileImpRecord(userId, filePath);

        // 写入数据库
        int insert = fileImpRecordService.insert(record);

        Map<String, Object> data = new HashMap<>();
        data.put("filePath", filePath);
        data.put("fileId", record.getId());
        return ResultBuilder.buildListSuccess(data);
    }

    /**
     * 上传用户头像
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/uploadProfilePhoto", consumes = {"multipart/form-data"})
    public ListResult<Object> uploadProfilePhoto(@RequestParam(name = "file", required = true) MultipartFile file)
        throws IOException {
        PageData pageData = getPageData();
        String userId = (String) pageData.get("userId");
        // TODO: 2021/1/6 上传图片到服务器上，并更新用户的头像信息
        String avatarUrl = fileService.uploadProfile(file, userId);
        Map<String, Object> data = new HashMap<>();
        data.put("avatarUrl", avatarUrl);
        return ResultBuilder.buildListSuccess(data);
    }

    /**
     * 农癌:上传附件
     *
     * @param file
     * @return
     */
    @PostMapping(value = "/uploadCerAttachmentFile")
    public ListResult<Object> uploadCerAttachmentFile(@RequestParam("file") MultipartFile file)
        throws IOException {
        PageData pageData = getPageData();
        String userId = (String) pageData.get("user");

        String path = fileService.uploadCerAttachmentFile(file, userId);

        String originalFilename = file.getOriginalFilename();

        String attachmentId = fileService.saveCerAttachmentFile(path, originalFilename);

        Map<String, Object> data = new HashMap<>();
        data.put("filePath", path);
        data.put("originalFilename", originalFilename);
        data.put("attachmentId", attachmentId);
        return ResultBuilder.buildListSuccess(data);
    }

    /**
     * 下载文件
     *
     * @param request          请求对象
     * @param response         响应对象
     * @param originalFilename 文件名称
     * @param url              下载URL
     */
    @PostMapping(path = "/downloadFile")
    public void downloadFile(HttpServletRequest request,
                             HttpServletResponse response,
                             @RequestParam(name = "originalFilename", required = true) String originalFilename,
                             @RequestParam(name = "url", required = true) String url) {
        try {
            FileUtils.downloadFile(originalFilename, url, response);
        } catch (Exception e) {
            log.warn(e.toString());
        }
    }

    /**
     * 查询文件类型名称
     *
     * @return
     */
    @GetMapping(path = "/queryFileTypeName")
    public ListResult<Object> queryFileTypeName() {
        List<LinkedHashMap<String, Object>> data = fileService.queryFileTypeName();
        return ResultBuilder.buildListSuccess(data);
    }

    /**
     * 获取可被允许上传的文件类型
     *
     * @return
     */
    @GetMapping(path = "/getFileSuffixs")
    public ListResult<Object> getFileSuffixs() {
        List<String> data = Arrays.asList("xls",
                                          "xlt",
                                          "et",
                                          "xlsx",
                                          "xltx",
                                          "csv",
                                          "xlsm",
                                          "xltm",
                                          "doc",
                                          "dot",
                                          "wps",
                                          "wpt",
                                          "docx",
                                          "dotx",
                                          "docm",
                                          "dotm",
                                          "ppt",
                                          "pptx",
                                          "pptm",
                                          "ppsx",
                                          "ppsm",
                                          "pps",
                                          "potx",
                                          "potm",
                                          "dpt",
                                          "dps",
                                          "pdf");
        return ResultBuilder.buildListSuccess(data);
    }

    /**
     * 创建新的文件夹
     *
     * @return
     */
    @RequestMapping("/createNewFolder")
    public ActionResult createNewFolder() {
        PageData pd = getPageData();
        String id = (String) pd.get("id");
        String originalFilename = (String) pd.get("originalFilename");
        String parentId = (String) pd.get("parentId");
        fileService.addFolder(Long.parseLong(id),
                              originalFilename,
                              parentId == null ? 0 : Long.parseLong(parentId));
        return ResultBuilder.buildActionSuccess();
    }

    /**
     * 返回文件导入记录的实体
     *
     * @param userId
     * @param filePath
     * @return
     */
    private CerFileImpRecord getFileImpRecord(String userId, String filePath) {
        CerFileImpRecord record = new CerFileImpRecord();
        record.setId(get32UUID());
        record.setTradeNo(get32UUID());
        record.setFilePath(filePath);
        record.setDisposeStatus(0);
        record.setCreateBy(userId);
        record.setDeleted(0);
        record.setVersion(1);
        record.setInsertDatetime(LocalDateTime.now());
        record.setLastUpdateDatetime(LocalDateTime.now());
        return record;
    }


}
